// packageStudent/pages/resume-add/index.js
import {chooseMessageFile} from "../../../utils/Wx";
import {uploader} from "../../../service/Common";
import {addResume} from "../../../service/Student";
import Toast from "@vant/weapp/toast/toast";
import Notify from "@vant/weapp/notify/notify";
import Dialog from "@vant/weapp/dialog/dialog";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        no: "",
        name: "",
        resume: {
            loading: false,
            text: "上传",
            path: ""
        },
        isSubmitLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        Dialog.alert({
            title: "上传说明",
            message: "将简历发送至微信，在本页面点击上传按钮，选择刚才发送的简历聊天对象，选择简历文件，点击确认即可上传成功",
        })
    },

    /*
    * 文件上传
    * */
    onResumeUploader: async function () {
        try {
            let tempFilePaths = await chooseMessageFile({
                count: 1,
                type: "file"
            });
            this.setData({"resume.loading": true})
            this.data.resume.path = await uploader(tempFilePaths[0].path);
            this.setData({"resume.text": "上传成功"})
        } catch (e) {
            this.setData({"resume.text": "上传失败"})
            console.error(e)
        } finally {
            this.setData({"resume.loading": false})
        }
    },

    /*
    * 选择
    * */
    bindSelectPosition: function () {
        const that = this;
        wx.navigateTo({
            url: "/pages/common/position-search/index",
            events: {
                acceptDataFromOpenedPage: function(data) {
                    console.log(data);
                    that.setData({name: data.positionName});
                    that.data.no = data.positionNo
                }
            },
        })
    },

    /*
    * 保存简历
    * */
    onSubmitButton: async function () {
        try {
            const that = this;
            let no = this.data.no;
            let name = this.data.name;
            let path = this.data.resume.path;
            let isSubmitLoading = this.data.isSubmitLoading;
            if (isSubmitLoading) {
                return false
            } else if (!name) {
                Notify("请选择应聘职位");
                return false
            } else if (!path) {
                Notify("请上传简历");
                return false
            }
            this.setData({isSubmitLoading: true});
            await addResume({
                no,
                name,
                path
            })
            Toast.success("保存成功！");
            setTimeout(function () {
                const eventChannel = that.getOpenerEventChannel()
                eventChannel.emit("acceptDataFromOpenedPage", {});
                wx.navigateBack();
            }, 1000)
        } catch (e) {
            Toast.fail("保存失败！");
            console.error(e)
        } finally {
            this.setData({isSubmitLoading: false});
        }
    }
})